package com.scs.application.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.sys.dto.DictDTO;
import com.scs.application.modules.sys.entity.DictData;
import com.scs.application.modules.sys.entity.DictType;
import com.scs.application.modules.sys.mapper.DictDataMapper;
import com.scs.application.modules.sys.mapper.DictTypeMapper;
import com.scs.application.modules.sys.service.DictTypeService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class DictTypeServiceImpl extends BaseServiceImpl<DictTypeMapper, DictType> implements DictTypeService {

    @Autowired
    private DictDataMapper dictDataMapper;

    @Override
    public boolean removeCascadeById(Serializable id) {
        dictDataMapper.delete(Wrappers.<DictData>query().eq("dict_type_id", id));
        return super.removeById(id);
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        dictDataMapper.delete(Wrappers.<DictData>query().in("dict_type_id", idList));
        return super.removeByIds(idList);
    }

    @Override
    public Boolean isSupport(Boolean flagProject) {
        return flagProject;
    }

    /**
     * 根据code获取字典实体
     *
     * @param dictTypeCode
     * @return
     */
    public DictDTO getDictDTOByCode(String dictTypeCode) {
        DictType dictType = this.getOne(Wrappers.<DictType>query().eq("code", dictTypeCode).last("limit 1"));
        if (dictType == null) {
            return null;
        }
        List<DictData> dictDataList = dictDataMapper.selectList(Wrappers.<DictData>query().eq("dict_type_id", dictType.getId()));

        DictDTO dictDTO = new DictDTO();
        BeanUtils.copyProperties(dictType, dictDTO);

        if (dictDataList != null && !dictDataList.isEmpty()) {
            dictDTO.setDictDataDTOS(Lists.newArrayListWithCapacity(dictDataList.size()));
            for(DictData dictData : dictDataList) {
                DictDTO.DictDataDTO dictDataDTO = new DictDTO.DictDataDTO();
                BeanUtils.copyProperties(dictData, dictDataDTO);
                dictDTO.getDictDataDTOS().add(dictDataDTO);
            }
        }
        return dictDTO;
    }

    public List<DictDTO> getDTOList() {
        return null;
    }

}
